package lib;

import java.io.IOException;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;

import model.DB;
import model.StaticInstances;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;

import com.blackberry.toolkit.ui.component.banner.Banner;

public class PageTemplate extends MainScreen
{
	private VerticalFieldManager _pane;
	final static long _defaultStyle = VERTICAL_SCROLL;
	
	public static final Background background = BackgroundFactory.createSolidBackground(Color.SILVER);//BackgroundFactory.createBitmapBackground(Bitmap.getBitmapResource("img/lightbluebkg.jpg"), Background.POSITION_X_LEFT, Background.POSITION_Y_TOP, Background.REPEAT_BOTH );//BackgroundFactory.createSolidBackground(Color.LIGHTBLUE);
	public Banner banner ;
	private static int batteryVisibility = Banner.PROPERTY_VALUE_DEFAULT;
	public static boolean bannerHasTitle = false;
	
	public static StaticInstances Instances;
	
	public PageTemplate(long style, boolean showBanner)
	{
		super(style);
		
		// Determine if an SDCard is present 
        boolean sdCardPresent = false;
        String root = null;
        Enumeration e = FileSystemRegistry.listRoots();
        while (e.hasMoreElements())
        {
            root = (String)e.nextElement();
            if(root.equalsIgnoreCase("sdcard/"))
            {
                sdCardPresent = true;
            }     
        }            
        if(!sdCardPresent)
        {
            UiApplication.getUiApplication().invokeLater(new Runnable()
            {
                public void run()
                {
                    Dialog.alert("This application requires an SD card to be present. Exiting application...");
                    System.exit(0);            
                } 
            });        
        }
		
		try {
			
			FileConnection fconn = (FileConnection) Connector.open(DB.DBLOCATION + "touchfile");
			if(!fconn.exists())
				fconn.create();
			
		} catch (Exception ex) 
		{
			System.out.println("Error creating dbLocation path: " + ex.getMessage());
		}
		
		if(Instances == null)
			Instances = StaticInstances.getInstance();
		
		setTitle("Bill Tracker", showBanner);
		doBackground();
	}
	
	public PageTemplate(boolean showBanner)
	{
		this(_defaultStyle, showBanner);
	}

	public void setTitle( String title, boolean showBanner )
    {
		if(showBanner)
		{
			banner = new Banner();
			banner.addTitle(title);
			bannerHasTitle = true;
			banner.setPropertyValue(Banner.PROPERTY_CELLULAR_VISIBILITY, Banner.PROPERTY_VALUE_ON);
			banner.setPropertyValue(Banner.PROPERTY_WIFI_VISIBILITY, Banner.PROPERTY_VALUE_ON);
			banner.addSignalIndicator();
			banner.setPropertyValue(Banner.PROPERTY_BATTERY_VISIBILITY, batteryVisibility);
			//banner.
			super.setBanner( banner );
		}
    }
	
	public void doBackground()
	{
		VerticalFieldManager internalField = new VerticalFieldManager( _defaultStyle )
		{
			protected void sublayout( int width, int height ) {
				
				int dispHeight = Display.getHeight() - banner.getPreferredHeight();
				super.sublayout(width, dispHeight);
				setExtent(width, dispHeight);
			}
			
		};
		_pane = new VerticalFieldManager( USE_ALL_WIDTH );
		internalField.setBackground(background);
		internalField.add(_pane);
		super.add( internalField );
		
	}
	
	public void add(Field f)
	{
		_pane.add(f);
		_pane.invalidate();
		this.invalidate();
	}
	
	public VerticalFieldManager getContainer()
	{
		return this._pane;
	}
	
	protected void pushScreen( Screen toPush ) 
    {
        UiApplication.getUiApplication().pushScreen( toPush );
    }
	
	public void switchScreen(final PageTemplate nextScreen)
	{
		final UiApplication ui = UiApplication.getUiApplication();
		if(ui.getActiveScreen()  instanceof PageTemplate )
		{
			final PageTemplate currentScreen = (PageTemplate)ui.getActiveScreen();
			if (UiApplication.isEventDispatchThread()) {  
	            ui.popScreen(currentScreen);  
	            ui.pushScreen(nextScreen);  
	        } else {  
	            ui.invokeLater(new Runnable() {  
	                public void run() {  
	                    ui.popScreen(currentScreen);  
	                    ui.pushScreen(nextScreen);  
	                }  
	            });  
	        } 
		}
	}

	public void popScreen()
	{
		final UiApplication ui = UiApplication.getUiApplication();
		if(ui.getActiveScreen()  instanceof PageTemplate )
		{
			final PageTemplate currentScreen = (PageTemplate)ui.getActiveScreen();
			if (UiApplication.isEventDispatchThread()) {  
	            ui.popScreen(currentScreen);
	        } else {  
	            ui.invokeLater(new Runnable() {  
	                public void run() {  
	                    ui.popScreen(currentScreen);
	                }  
	            });  
	        } 
        } 
	}
}
